package com.ujs.code.minSubArrayLen;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangshihao
 * @create 2023-09-24 15:48
 */
public class TotalFruit {
    public static void main(String[] args) {
        int[] fruits = {0, 1, 6, 6, 4, 4, 6};
        // 3,3,3,1,2,1,1,2,3,3,4
        // 0,1,6,6,4,4,6
        // 3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4
        int i = totalFruit(fruits);
        System.out.println(i);
    }

    /**
     * 滑动窗口
     *
     * @param fruits
     * @return
     */
    public static int totalFruit(int[] fruits) {
        int n = fruits.length;
        int start = 0;
        int fruit1 = -1, fruit2 = -1;
        int end = 0; // 水果的类型第一次发生改变的地方
        for (int i = 0; i < n - 1; i++) {
            if (fruits[i] != fruits[i + 1]) {
                end = i + 1;
                fruit1 = fruits[i];
                fruit2 = fruits[i + 1];
                break;
            }
        }
        if (end == n) {
            return n;
        }
        int max = 0;
        while (end < n - 1) {
            if (fruit1 != fruits[end + 1] && fruit2 != fruits[end + 1]) {
                if (end - start + 1 > max) {
                    max = end - start + 1;
                }
                for (int i = start; i < n; i++) {
                    if (fruits[i] != fruits[end]) {
                        start = i;
                        break;
                    }
                }
                fruit1 = fruits[end];
                fruit2 = fruits[end + 1];
            }
            end++;
        }
        return Math.max(max, end - start + 1);
    }

    public static int totalFruit2(int[] fruits) {
        int n = fruits.length;
        Map<Integer, Integer> cnt = new HashMap<>();

        int left = 0, ans = 0;
        for (int right = 0; right < n; right++) {
            cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
            while (cnt.size() > 2) {
                cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
                if (cnt.get(fruits[left]) == 0) {
                    cnt.remove(fruits[left]);
                }
                left++;
            }
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }
}
